package demo02.util;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Created by 抽离on 2017/3/8 0008.
 */
public class StringUtil {
    
    public static void main(String[] args){
        System.out.println("----------=" + getRandomCode());
    }
    // 定义下划线
    private static final char UNDERLINE = '_';

    public static String getRandomCode(){
        return (int)((Math.random()*9+1)*100000) + "";
    }

    public static int getNum(int start,int end) {
        return (int)(Math.random()*(end-start+1)+start);
    }

    /**
     * 返回手机号码
     */
    public static String[] telFirst="134,135,136,137,138,139,150,151,152,157,158,159,130,131,132,155,156,133,153".split(",");
    public static String randomTel() {
        int index=getNum(0,telFirst.length-1);
        String first=telFirst[index];
        String second=String.valueOf(getNum(1,888)+10000).substring(1);
        String thrid=String.valueOf(getNum(1,9100)+10000).substring(1);
        return first+second+thrid;
    }

    /**
     * 含数字的随机字符串
     */
    public static String randomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();

        for(int i = 0 ; i < length; ++i){
            int number = random.nextInt(62);//[0,62)

            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 不含数字的随机字符串
     */
    public static String randomNoNumString(int length){
        String str="abcdefghijklmnopqrstuvwxyz";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();

        for(int i = 0 ; i < length; ++i){
            int number = random.nextInt(26);//[0,26)

            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 数字前面加0转成字符串
     */
    public static String addPrefix(Integer value, int num) {
        String ret = String.valueOf(value);

        for (int i = 0, len = num - ret.length(); i < len; i++) {
            ret = "0" + ret;
        }

        return ret;
    }

    /**
     * 转换为中文数字
     *
     * @param num -> 二十五
     * @return
     */
    public static String formatInteger(int num) {
        String[] units = { "", "十", "百", "千", "万", "十万", "百万", "千万", "亿", "十亿", "百亿", "千亿", "万亿" };
        char[] numArray = { '零', '一', '二', '三', '四', '五', '六', '七', '八', '九' };
        char[] val = String.valueOf(num).toCharArray();
        int len = val.length;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            String m = val[i] + "";
            int n = Integer.valueOf(m);
            boolean isZero = n == 0;
            String unit = units[(len - 1) - i];
            if (isZero) {
                if ('0' == val[i - 1]) {
                    continue;
                } else {
                    sb.append(numArray[n]);
                }
            } else {
                sb.append(numArray[n]);
                sb.append(unit);
            }
        }
        return sb.toString();
    }

    /**
     * 格式化电话 13855556666 -》 138 5555 6666
     *
     * @param tel
     * @return
     */
    public static String formatTel(String tel) {
        if (tel == null)
            return "";
        StringBuffer sb = new StringBuffer(tel);
        if (sb.length() > 2)
            sb.insert(3, " ");
        if (sb.length() > 7)
            sb.insert(8, " ");
        if (sb.length() > 12)
            sb.insert(13, " ");
        return sb.toString();
    }

    public static String filter(String str) throws PatternSyntaxException {
        if(str == null) return "";
        // 清除掉所有特殊字符
        String regEx = "[ `~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static Integer parseInt(String str) {
        try {
            return new Integer(Pattern.compile("[^0-9]").matcher(str).replaceAll(""));
        } catch(Exception e) {
            return null;
        }
    }

    public static Double parseDouble(String str) {
        try {
            return new Double(Pattern.compile("[^\\.0-9]").matcher(str).replaceAll(""));
        } catch(Exception e) {
            return null;
        }
    }

    /**
     * 检测是否有emoji字符
     * @param source
     * @return 一旦含有就抛出
     */
    public static boolean containsEmoji(String source) {
        if (StringUtils.isBlank(source)) {
            return false;
        }

        int len = source.length();

        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);

            if (isEmojiCharacter(codePoint)) {
                //do nothing，判断到了这里表明，确认有表情字符
                return true;
            }
        }

        return false;
    }


    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }

    /**
     * 过滤emoji 或者 其他非文字类型的字符
     * @param source
     * @return
     */
    public static String filterEmoji(String source) {

        if (!containsEmoji(source)) {
            return source;//如果不包含，直接返回
        }
        //到这里铁定包含
        StringBuilder buf = null;

        int len = source.length();

        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);

            if (isEmojiCharacter(codePoint)) {
                if (buf == null) {
                    buf = new StringBuilder(source.length());
                }

                buf.append(codePoint);
            } else {
            }
        }

        if (buf == null) {
            return source;//如果没有找到 emoji表情，则返回源字符串
        } else {
            if (buf.length() == len) {//这里的意义在于尽可能少的toString，因为会重新生成字符串
                buf = null;
                return source;
            } else {
                return buf.toString();
            }
        }
    }

    /**
     * String为空判断
     *
     * @param str 需判断字符串
     * @return true:为空 false:不为空
     */
    public static boolean isEmpty(String str) {
        return str == null || "".equals(str.trim());
    }

    /**
     * String不为空判断
     *
     * @param str 需判断字符串
     * @return true:不为空 false:为空
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    /**
     * 驼峰转下划线工具
     *
     * @param param 需要转换的字符串
     * @return 转换好的字符串
     */
    public static String camelToUnderline(String param) {
        if (isNotEmpty(param)) {
            int len = param.length();
            StringBuilder sb = new StringBuilder(len);

            for (int i = 0; i < len; ++i) {
                char c = param.charAt(i);
                if (Character.isUpperCase(c)) {
                    sb.append(UNDERLINE);
                    sb.append(Character.toLowerCase(c));
                } else {
                    sb.append(c);
                }
            }

            return sb.toString();
        } else {
            return "";
        }
    }

    /**
     * 下划线转驼峰工具
     *
     * @param param 需要转换的字符串
     * @return 转换好的字符串
     */
    public static String underlineToCamel(String param) {
        if (isNotEmpty(param)) {
            int len = param.length();
            StringBuilder sb = new StringBuilder(len);

            for (int i = 0; i < len; ++i) {
                char c = param.charAt(i);
                if (c == 95) {
                    ++i;
                    if (i < len) {
                        sb.append(Character.toUpperCase(param.charAt(i)));
                    }
                } else {
                    sb.append(c);
                }
            }

            return sb.toString();
        } else {
            return "";
        }
    }


    /**
     * 在字符串两周添加''
     *
     * @param param 字符串
     * @return 处理后的字符串
     */
    public static String addSingleQuotes(String param) {
        return "\'" + param + "\'";
    }

    public static String unicode2String(String unicode) {

        StringBuffer string = new StringBuffer();

        String[] hex = unicode.split("\\\\u");

        for (int i = 1; i < hex.length; i++) {

            // 转换出每一个代码点
            int data = Integer.parseInt(hex[i], 16);

            // 追加成string
            string.append((char) data);
        }

        return string.toString();
    }

    public static  Map<String, String> getCookies(){
        Map<String, String> cookies = null;
        Connection.Response res = null;
        try {
            res = Jsoup.connect("http://xm.anjuke.com/tycoon/").timeout(30000).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        cookies = res.cookies();
        return  cookies;
    }

    public static  String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "/n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static boolean isboolIp(String ipAddress) {
        String ip = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
        Pattern pattern = Pattern.compile(ip);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
    }

    public static String processCorpNameNil(String raw){
        if(raw==null || "".equals(raw)){
            return null;
        }
        String a = raw.replaceAll("有限","")
                .replaceAll("公司","")
                .replaceAll("行销策划","")
                .replaceAll("营销策划","")
                .replaceAll("投资管理","")
                .replaceAll("物业管理","")
                .replaceAll("租售中心","")
                .replaceAll("物业","")
                .replaceAll("集团","")
                .replaceAll("信息服务","")
                .replaceAll("厦门","")
                .replaceAll("市","")
                .replaceAll("（","")
                .replaceAll("）","")
                .replaceAll("\\(","")
                .replaceAll("\\)","")
                .replaceAll("不动产.*","")
                .replaceAll("房地产.*","")
                .replaceAll("房产.*","")
                .replaceAll("地产.*","")
                .replaceAll("置业.*","")
                .replaceAll("房屋.*","")
                .replaceAll("经纪人","")
                .trim();

        if(a.contains("个人")){
            a = null;
        }
        else if(a==null || "".equals(a)){
            a = null;
        }

        return a;
    }

    public static String processCorpName(String raw){
        if(raw==null || "".equals(raw)){
            return "其他";
        }
        String a = raw.replaceAll("有限","")
                .replaceAll("公司","")
                .replaceAll("行销策划","")
                .replaceAll("营销策划","")
                .replaceAll("投资管理","")
                .replaceAll("物业管理","")
                .replaceAll("租售中心","")
                .replaceAll("物业","")
                .replaceAll("集团","")
                .replaceAll("信息服务","")
                .replaceAll("厦门","")
                .replaceAll("市","")
                .replaceAll("（","")
                .replaceAll("）","")
                .replaceAll("\\(","")
                .replaceAll("\\)","")
                .replaceAll("不动产.*","")
                .replaceAll("房地产.*","")
                .replaceAll("房产.*","")
                .replaceAll("地产.*","")
                .replaceAll("置业.*","")
                .replaceAll("房屋.*","")
                .replaceAll("经纪人","")
                .trim();

        if(a.contains("个人")){
            a = "个人";
        }
        else if(a==null || "".equals(a)){
            a = "其他";
        }

        return a;
    }
}
